'use strict';

module.exports = app => {
  const BaseController = require('../../controller/base');
  class ChatController extends BaseController {

    // 聊天记录创建，新增
    async index() {
      const ctx = this.ctx;
      const self = this;
      ctx.set('Content-Type', 'application/json');
      const message = this.ctx.args[0];
      const socket = this.ctx.socket;
      const onlineUsers = this.app.config.onlineUsers;

      socket.on("res", function (data) {
        // 把消息添加到数据库
        var obj = {
          number: socket.name,
          name: onlineUsers[socket.name],
          msg: data
        };

        var msg = ctx.service.chat.new(obj);
        // self.success({
        //   msg: "发送消息成功"
        // })
        // 添加成功后，广播消息
        socket.broadcast.emit("res", data);
      });
    }

    // 客户掉线
    async disconnect() {
      const onlineUsers = this.app.config.onlineUsers;
      const socket = this.ctx.socket;
      //将退出的用户从在线列表中删除
      if (onlineUsers.hasOwnProperty(socket.name)) {
        //退出用户的信息
        var obj = {
          id: socket.name,
          name: onlineUsers[socket.name]
        };
        //删除
        delete onlineUsers[socket.name];
        //向所有客户端广播用户退出
        socket.broadcast.emit('logout', obj);
      }
    }

  }
  return ChatController;
};
